<!DOCTYPE html>
<html>
<head>
    <title>双向通信测试页面</title>
    <meta charset="utf-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
        
        h1, h2 {
            color: #333;
        }
        
        .section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        button {
            padding: 10px 15px;
            margin: 5px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        
        button:hover {
            background: #0056b3;
        }
        
        .result {
            margin-top: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
            min-height: 50px;
        }
        
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
    </style>
</head>
<body>
    <h1>Flutter-JavaScript 双向通信测试</h1>
    
    <div id="bridgeStatus" class="status info">
        正在检查 Flutter 通信桥状态...
    </div>
    
    <div class="section">
        <h2>1. JavaScript 调用 Flutter 方法</h2>
        
        <button onclick="testShowToast()">测试 Toast 消息</button>
        <button onclick="testGetDeviceInfo()">获取设备信息</button>
        <button onclick="testCalculate()">数学计算测试</button>
        <button onclick="testSaveUserData()">保存用户数据</button>
        
        <div class="result" id="flutterResult">等待操作...</div>
    </div>
    
    <div class="section">
        <h2>2. Flutter 调用 JavaScript 方法</h2>
        <p>请在 Flutter 端使用以下方法调用：</p>
        <code>await callJavaScriptMethod('showAlert', '测试消息');</code>
        <br>
        <code>await callJavaScriptMethod('getUserData', {userId: 123});</code>
        
        <div class="result" id="jsResult">等待 Flutter 调用...</div>
    </div>
    
    <div class="section">
        <h2>3. 完整通信测试</h2>
        <button onclick="runCompleteTest()">运行完整测试</button>
        
        <div class="result" id="completeTestResult">等待测试...</div>
    </div>

    <script>
        // 检查通信桥状态
        function checkBridgeStatus() {
            if (window.flutter_inappwebview) {
                document.getElementById('bridgeStatus').className = 'status success';
                document.getElementById('bridgeStatus').innerHTML = 
                    '✅ Flutter 通信桥已初始化！可以开始测试。';
                return true;
            } else {
                document.getElementById('bridgeStatus').className = 'status error';
                document.getElementById('bridgeStatus').innerHTML = 
                    '❌ Flutter 通信桥未初始化。请确保在 Flutter WebView 中加载此页面。';
                return false;
            }
        }
        
        // 注册 JavaScript 方法供 Flutter 调用
        if (window.FlutterJSChannel) {
            window.FlutterJSChannel.registerMethod('showAlert', function(message) {
                document.getElementById('jsResult').innerHTML = 
                    `Flutter 调用了 showAlert 方法: ${message}`;
                alert(`来自 Flutter 的消息: ${message}`);
                return 'Alert shown successfully';
            });
            
            window.FlutterJSChannel.registerMethod('getUserData', function(params) {
                const result = {
                    userId: params.userId || 0,
                    name: "测试用户",
                    email: "test@example.com",
                    timestamp: new Date().toISOString()
                };
                document.getElementById('jsResult').innerHTML = 
                    `Flutter 请求用户数据: ${JSON.stringify(result, null, 2)}`;
                return result;
            });
        }
        
        // 测试方法
        function testShowToast() {
            if (!checkBridgeStatus()) return;
            
            window.flutter_inappwebview.callHandler("showToast", "Hello from JavaScript测试!");
            document.getElementById('flutterResult').innerHTML = "Toast 消息已发送";
        }
        
        function testGetDeviceInfo() {
            if (!checkBridgeStatus()) return;
            
            window.flutter_inappwebview.callHandler("getDeviceInfo")
                .then(result => {
                    document.getElementById('flutterResult').innerHTML = 
                        `<strong>设备信息:</strong><br><pre>${JSON.stringify(result, null, 2)}</pre>`;
                })
                .catch(error => {
                    document.getElementById('flutterResult').innerHTML = 
                        `获取设备信息失败: ${error}`;
                });
        }
        
        function testCalculate() {
            if (!checkBridgeStatus()) return;
            
            window.flutter_inappwebview.callHandler("calculate", 15, 3, "multiply")
                .then(result => {
                    document.getElementById('flutterResult').innerHTML = 
                        `计算结果: 15 * 3 = ${result}`;
                })
                .catch(error => {
                    document.getElementById('flutterResult').innerHTML = 
                        `计算失败: ${error}`;
                });
        }
        
        function testSaveUserData() {
            if (!checkBridgeStatus()) return;
            
            const userData = {
                name: "测试用户",
                age: 30,
                email: "test.user@example.com",
                preferences: {
                    theme: "dark",
                    language: "zh-CN"
                }
            };
            
            window.flutter_inappwebview.callHandler("saveUserData", userData)
                .then(result => {
                    document.getElementById('flutterResult').innerHTML = 
                        `<strong>保存结果:</strong><br><pre>${JSON.stringify(result, null, 2)}</pre>`;
                })
                .catch(error => {
                    document.getElementById('flutterResult').innerHTML = 
                        `保存失败: ${error}`;
                });
        }
        
        function runCompleteTest() {
            if (!checkBridgeStatus()) return;
            
            const testResults = [];
            const startTime = Date.now();
            
            document.getElementById('completeTestResult').innerHTML = "开始完整测试...";
            
            // 执行一系列测试
            const tests = [
                () => testShowToast(),
                () => testGetDeviceInfo(),
                () => testCalculate(),
                () => testSaveUserData()
            ];
            
            let currentTest = 0;
            
            function runNextTest() {
                if (currentTest < tests.length) {
                    tests[currentTest]();
                    currentTest++;
                    setTimeout(runNextTest, 1000);
                } else {
                    const duration = Date.now() - startTime;
                    document.getElementById('completeTestResult').innerHTML = 
                        `✅ 完整测试完成！耗时: ${duration}ms`;
                }
            }
            
            runNextTest();
        }
        
        // 初始化检查
        setTimeout(checkBridgeStatus, 1000);
        
        console.log('测试页面已加载，等待通信桥初始化...');
    </script>
</body>
</html>